﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Discuz.Toolkit;
using Icst.Leaflike.Discuz;

namespace Icst.Leaflike.Web
{
    public partial class register : pagebase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                errorPanel.Style[HtmlTextWriterStyle.Display] = "none";
            }
        }
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            string returnUrl = this.Para("returnUrl", "index.htm");
            string error = string.Empty;
            string userName = txtUserName.Value.Trim();
            string email = txtEmail.Value.Trim();
            string password = txtPassword.Value.Trim();

            if (!VerifyCheck(txtVerifyCode.Value.Trim()))
            {
                errorPanel.Style[HtmlTextWriterStyle.Display] = "";
                lblError.InnerText = "请输入正确的验证码";
                return;
            }

            if (UserAccount.Register(email, userName, password, out error))
            {
                DoLogin(userName, password);

                this.Redirect(returnUrl);
            }
            else
            {
                errorPanel.Style[HtmlTextWriterStyle.Display] = "";
                lblError.InnerText = error;
            }
        }
        private bool VerifyCheck(string verifyCode)
        {
            string targetverifyCode = Session["VerificationCode"] != null ? (string)Session["VerificationCode"] : string.Empty;
            return (!string.IsNullOrEmpty(targetverifyCode) &&
                verifyCode.Equals(targetverifyCode, StringComparison.InvariantCultureIgnoreCase));
        }
        private bool DoLogin(string userName, string password)
        {
            try
            {
                if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
                    return false;

                User user = null;
                return UserAccount.Login(userName, password, out user);
            }
            catch
            {
                return false;
            }
        }
    }
}
